package com.imooc.miaosha.rabbitmq;

import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.domain.OrderInfo;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.service.RedisService;
import com.imooc.miaosha.vo.MiaoshaGoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Paul
 * @version 0.1
 * @date 2018/3/22 0022
 */
@Service
@Slf4j
public class MQReceiver {
    private final GoodsService goodsService;
    private final OrderService orderService;
    private final MiaoshaService miaoshaService;

    @Autowired
    public MQReceiver(GoodsService goodsService, OrderService orderService, MiaoshaService miaoshaService) {
        this.goodsService = goodsService;
        this.orderService = orderService;
        this.miaoshaService = miaoshaService;
    }

//    @RabbitListener(queues = MQConfig.QUEUE)
//    public void receive(String msg) {
//        log.info("收到消息queue=" + msg);
//    }
//
//    @RabbitListener(queues = "topic.queue1")
//    public void receiveTopic1(String msg) {
//        log.info("收到消息topic.queue1=" + msg);
//    }
//
//    @RabbitListener(queues = "topic.queue2")
//    public void receiveTopic2(String msg) {
//        log.info("收到消息topic.queue2=" + msg);
//    }
//
//    @RabbitListener(queues = "fanout.queue1")
//    public void receiveFanout1(String msg) {
//        log.info("收到消息fanout.queue1=" + msg);
//    }
//
//    @RabbitListener(queues = "fanout.queue2")
//    public void receiveFanout2(String msg) {
//        log.info("收到消息fanout.queue2=" + msg);
//    }
//
//    @RabbitListener(queues = "headers.queue1")
//    public void receiveHeader1(byte[] bytes) {
//        log.info("收到消息headers.queue1=" + new String(bytes));
//    }

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaosha(String msg) {
        log.info("收到消息queue=" + msg);
        MiaoshaMessage miaoshaMessage = RedisService.stringToBean(msg, MiaoshaMessage.class);
        long goodsId = miaoshaMessage.getGoodsId();
        MiaoshaUser miaoshaUser = miaoshaMessage.getMiaoshaUser();
        MiaoshaGoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdAndGoodsId(miaoshaUser.getId(), goodsId);
        if (order != null) {
            return;
        }
        //在队列中执行秒杀
        miaoshaService.miaosha(miaoshaUser, goodsId);
    }

}
